<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>发布图文 - 小红书风格</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
      padding: 20px;
    }

    /* 添加模态框样式 */
    .modal {
      display: none;
      position: fixed;
      z-index: 1000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
    }

    .modal-content {
      background-color: #fff;
      margin: auto;
      padding: 20px;
      border: none;
      border-radius: 10px;
      width: 300px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
    }

    .close-btn {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
      position: absolute;
      top: 10px;
      right: 15px;
    }

    .close-btn:hover {
      color: #000;
    }

    #qrcode {
      width: 100%;
      height: auto;
      margin-top: 10px;
    }

    .container {
      max-width: 1400px;
      margin: 0 auto;
      background: white;
      border-radius: 20px;
      box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
      overflow: hidden;
    }

    .header {
      background: linear-gradient(45deg, #ff6b6b, #ff8e8e);
      padding: 30px;
      text-align: center;
      color: white;
    }

    .header h1 {
      font-size: 28px;
      font-weight: 600;
      margin-bottom: 10px;
    }

    .header p {
      opacity: 0.9;
      font-size: 16px;
    }

    .main-content {
      display: grid;
      grid-template-columns: 1fr 400px;
      gap: 0;
    }

    .form-section {
      padding: 40px;
      display: flex;
      flex-direction: column;
      gap: 25px;
    }

    .preview-section {
      background: #f8f9fa;
      padding: 40px 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .section-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
      margin-bottom: 15px;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .section-title::before {
      content: '';
      width: 4px;
      height: 20px;
      background: linear-gradient(45deg, #ff6b6b, #ff8e8e);
      border-radius: 2px;
    }

    .image-upload {
      border: 2px dashed #ddd;
      border-radius: 15px;
      padding: 40px;
      text-align: center;
      transition: all 0.3s ease;
      cursor: pointer;
      background: #fafafa;
    }

    .image-upload:hover {
      border-color: #ff6b6b;
      background: #fff5f5;
    }

    .image-upload.dragover {
      border-color: #ff6b6b;
      background: #fff5f5;
      transform: scale(1.02);
    }

    .upload-icon {
      font-size: 48px;
      color: #ccc;
      margin-bottom: 15px;
    }

    .upload-text {
      color: #666;
      font-size: 16px;
      margin-bottom: 10px;
    }

    .upload-hint {
      color: #999;
      font-size: 14px;
    }

    .image-preview {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
      gap: 10px;
      margin-top: 20px;
    }

    .preview-item {
      position: relative;
      border-radius: 10px;
      overflow: hidden;
      aspect-ratio: 1;
    }

    .preview-item img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .remove-btn {
      position: absolute;
      top: 5px;
      right: 5px;
      background: rgba(255, 107, 107, 0.9);
      color: white;
      border: none;
      border-radius: 50%;
      width: 24px;
      height: 24px;
      font-size: 16px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .form-group {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    .form-label {
      font-weight: 500;
      color: #333;
      font-size: 14px;
    }

    .form-input, .form-textarea {
      padding: 12px 16px;
      border: 2px solid #eee;
      border-radius: 10px;
      font-size: 14px;
      transition: all 0.3s ease;
      font-family: inherit;
    }

    .form-input:focus, .form-textarea:focus {
      outline: none;
      border-color: #ff6b6b;
      box-shadow: 0 0 0 3px rgba(255, 107, 107, 0.1);
      transition: all 0.3s ease;
    }

    .form-input.active-field, .form-textarea.active-field {
      border-color: #ff6b6b;
      background: linear-gradient(135deg, #fff5f5 0%, #ffffff 100%);
      box-shadow: 0 0 0 3px rgba(255, 107, 107, 0.15);
    }

    .form-textarea {
      resize: vertical;
      min-height: 120px;
    }

    .tags-container {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-top: 10px;
    }

    .tag {
      background: #f0f0f0;
      color: #666;
      padding: 6px 12px;
      border-radius: 20px;
      font-size: 12px;
      display: flex;
      align-items: center;
      gap: 6px;
    }

    .tag .remove-tag {
      background: none;
      border: none;
      color: #999;
      cursor: pointer;
      font-size: 14px;
      padding: 0;
      width: 16px;
      height: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .tag-input {
      background: none;
      border: none;
      outline: none;
      font-size: 12px;
      color: #666;
      min-width: 80px;
    }

    .location-input {
      position: relative;
    }

    .location-icon {
      position: absolute;
      left: 12px;
      top: 50%;
      transform: translateY(-50%);
      color: #999;
    }

    .location-input .form-input {
      padding-left: 40px;
    }

    .publish-btn {
      background: linear-gradient(45deg, #ff6b6b, #ff8e8e);
      color: white;
      border: none;
      padding: 15px 40px;
      border-radius: 25px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      margin-top: 30px;
      align-self: center;
    }

    .publish-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 10px 20px rgba(255, 107, 107, 0.3);
    }

    .publish-btn:disabled {
      opacity: 0.6;
      cursor: not-allowed;
      transform: none;
    }

    .char-counter {
      text-align: right;
      font-size: 12px;
      color: #999;
      margin-top: 5px;
    }

    .char-counter.warning {
      color: #ff6b6b;
    }

    /* 手机预览样式 */
    .mobile-preview {
      background: #fff;
      border-radius: 25px;
      padding: 15px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
      max-width: 375px;
      width: 100%;
      position: sticky;
      top: 20px;
    }

    .mobile-frame {
      border: 3px solid #333;
      border-radius: 20px;
      overflow: hidden;
      background: #000;
    }

    .mobile-screen {
      background: #fff;
      min-height: 600px;
    }

    .mobile-header {
      background: #fff;
      padding: 15px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .mobile-avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: linear-gradient(45deg, #ff6b6b, #ff8e8e);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 14px;
      font-weight: bold;
    }

    .mobile-user-info {
      flex: 1;
    }

    .mobile-username {
      font-size: 14px;
      font-weight: 600;
      color: #333;
    }

    .mobile-time {
      font-size: 12px;
      color: #999;
    }

    .mobile-follow {
      background: #ff2442;
      color: white;
      border: none;
      padding: 6px 12px;
      border-radius: 15px;
      font-size: 12px;
      cursor: pointer;
    }

    .mobile-images {
      position: relative;
      background: #f8f8f8;
    }

    .mobile-image-container {
      position: relative;
      padding-bottom: 100%;
      overflow: hidden;
    }

    .mobile-image {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .mobile-image-indicator {
      position: absolute;
      bottom: 10px;
      right: 10px;
      background: rgba(0, 0, 0, 0.6);
      color: white;
      padding: 4px 8px;
      border-radius: 10px;
      font-size: 11px;
    }

    .mobile-content {
      padding: 15px;
    }

    .mobile-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 10px;
      line-height: 1.4;
    }

    .mobile-text {
      font-size: 14px;
      color: #666;
      line-height: 1.6;
      margin-bottom: 12px;
      white-space: pre-wrap;
    }

    .mobile-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 6px;
      margin-bottom: 12px;
    }

    .mobile-tag {
      background: #f0f8ff;
      color: #0066cc;
      padding: 4px 8px;
      border-radius: 12px;
      font-size: 12px;
    }

    .mobile-location {
      display: flex;
      align-items: center;
      gap: 5px;
      color: #666;
      font-size: 12px;
      margin-bottom: 15px;
    }

    .mobile-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px;
      border-top: 1px solid #f0f0f0;
    }

    .mobile-action {
      display: flex;
      align-items: center;
      gap: 5px;
      color: #666;
      font-size: 12px;
      cursor: pointer;
    }

    .mobile-action:hover {
      color: #ff2442;
    }

    .preview-title {
      text-align: center;
      margin-bottom: 20px;
      color: #333;
      font-size: 16px;
      font-weight: 600;
      position: relative;
    }

    .preview-updating {
      position: absolute;
      top: 0;
      right: 0;
      background: #ff6b6b;
      color: white;
      padding: 4px 8px;
      border-radius: 10px;
      font-size: 10px;
      font-weight: normal;
      opacity: 0;
      transition: opacity 0.3s ease;
    }

    .preview-updating.show {
      opacity: 1;
    }

    .preview-toggle {
      position: fixed;
      bottom: 20px;
      right: 20px;
      background: linear-gradient(45deg, #ff6b6b, #ff8e8e);
      color: white;
      border: none;
      padding: 12px 20px;
      border-radius: 25px;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      box-shadow: 0 5px 15px rgba(255, 107, 107, 0.3);
      z-index: 1000;
      display: none;
      transition: all 0.3s ease;
    }

    .preview-toggle:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 20px rgba(255, 107, 107, 0.4);
    }

    @media (max-width: 1024px) {
      .main-content {
        grid-template-columns: 1fr;
      }

      .preview-section {
        display: none;
      }

      .preview-toggle {
        display: block;
      }

      .preview-section.mobile-show {
        display: flex;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.8);
        z-index: 999;
        padding: 20px;
      }

      .preview-close {
        position: absolute;
        top: 20px;
        right: 20px;
        background: rgba(255, 255, 255, 0.9);
        border: none;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        font-size: 20px;
        cursor: pointer;
        z-index: 1001;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    @media (max-width: 768px) {
      .form-section {
        padding: 20px;
      }

      .header {
        padding: 20px;
      }

      .header h1 {
        font-size: 24px;
      }
    }

    .hidden {
      display: none !important;
    }

    .upload-progress {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(255, 107, 107, 0.9);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      font-weight: 600;
      opacity: 0;
      transition: opacity 0.3s ease;
      pointer-events: none;
    }

    .upload-progress.show {
      opacity: 1;
    }

    .upload-success {
      background: rgba(76, 175, 80, 0.9) !important;
    }

    .upload-error {
      background: rgba(244, 67, 54, 0.9) !important;
    }

    .no-images {
      text-align: center;
      padding: 40px 20px;
      color: #999;
      font-size: 14px;
    }

    .no-images-icon {
      font-size: 48px;
      margin-bottom: 10px;
      opacity: 0.5;
    }
  </style>
</head>
<body>
<div class="container">
  <div class="header">
    <h1>✨ 发布图文笔记</h1>
    <p>分享你的生活点滴，记录美好时光</p>
  </div>

  <div class="main-content">
    <div class="form-section">
      <form id="publishForm">
        <div class="section-title">📸 选择图片</div>
        <div class="image-upload" id="imageUpload">
          <div class="upload-progress" id="uploadProgress"></div>
          <div class="upload-icon">📷</div>
          <div class="upload-text">点击或拖拽上传图片</div>
          <div class="upload-hint">支持 JPG、PNG、GIF 格式，最多9张</div>
          <input type="file" id="fileInput" multiple accept="image/*" class="hidden">
        </div>
        <div class="image-preview" id="imagePreview"></div>

        <div class="form-group">
          <div class="section-title">✏️ 标题</div>
          <input type="text" class="form-input" id="title"
                 placeholder="给你的笔记起个吸引人的标题..." maxlength="50">
          <div class="char-counter" id="titleCounter">0/50</div>
        </div>

        <div class="form-group">
          <div class="section-title">📝 正文内容</div>
          <textarea class="form-textarea" id="content" placeholder="分享你的想法、感受或经验...

💡 小贴士：
• 使用 emoji 让内容更生动
• 分段让阅读更轻松
• 添加相关话题标签" maxlength="1000"></textarea>
          <div class="char-counter" id="contentCounter">0/1000</div>
        </div>

        <div class="form-group">
          <div class="section-title">🏷️ 话题标签</div>
          <input type="text" class="form-input" id="tagsInput"
                 placeholder="添加话题标签，按回车确认">
          <div class="tags-container" id="tagsContainer"></div>
        </div>

        <div class="form-group">
          <div class="section-title">📍 位置</div>
          <div class="location-input">
            <span class="location-icon">📍</span>
            <input type="text" class="form-input" id="location" placeholder="添加位置信息（可选）">
          </div>
        </div>

        <button type="submit" class="publish-btn" id="publishBtn">🚀 发布笔记</button>
      </form>
    </div>

    <div class="preview-section" id="previewSection">
      <button type="button" class="preview-close" onclick="publisher.togglePreview()">×</button>
      <div class="preview-title">
        📱 手机预览
        <span class="preview-updating" id="previewUpdating">更新中...</span>
      </div>
      <div class="mobile-preview">
        <div class="mobile-frame">
          <div class="mobile-screen" id="mobileScreen">
            <div class="no-images">
              <div class="no-images-icon">📱</div>
              <div>左侧添加图片查看预览效果</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<button type="button" class="preview-toggle" id="previewToggle">👁️ 预览</button>

<div id="loginModal" class="modal">
  <div class="modal-content">
    <span class="close-btn">&times;</span>
    <h2>Scan to Login</h2>
    <img id="qrcode" src="" alt="QR Code">
  </div>
</div>
<script>
  const qrcodeImg = document.getElementById('qrcode');
  const modal = document.getElementById('loginModal');
  let loginCheckInterval;

  // 页面加载时自动获取二维码
  window.addEventListener('load', () => {
    // 自动获取二维码
    fetch('/auto/login')
    .then(response => {
      if (response.ok) {
        return response.blob();
      }
      throw new Error('Network response was not ok.');
    })
    .then(blob => {
      const imageUrl = URL.createObjectURL(blob);
      qrcodeImg.src = imageUrl;
      modal.style.display = 'block';
      // 启动轮询检查登录状态
      startLoginCheck();
    })
    .catch(error => console.error('Error fetching QR code:', error));
  });

  // 启动登录状态检查
  function startLoginCheck() {
    loginCheckInterval = setInterval(() => {
      fetch('/auto/login')
      .then(response => {
        if (response.ok) {
          return response.blob();
        }
        throw new Error('Network response was not ok.');
      })
      .then(blob => {
        // 如果仍然返回图片，说明未登录成功，继续轮询
        // 如果需要检测登录状态，应该由后端提供专门的状态检查接口
        const imageUrl = URL.createObjectURL(blob);
        qrcodeImg.src = imageUrl;
      })
      .catch(error => {
        console.error('Error checking login status:', error);
      });
    }, 3000); // 每3秒检查一次
  }

  // 关闭按钮事件
  document.querySelector('.close-btn').addEventListener('click', () => {
    modal.style.display = 'none';
    clearInterval(loginCheckInterval);
  });

  class XiaohongshuPublisher {
    constructor() {
      this.images = [];
      this.tags = [];
      this.maxImages = 9;
      this.previewDebounceTimer = null;
      this.lastPreviewUpdate = 0;
      this.uploadProgress = null;
      this.init();
    }

    init() {
      console.log('Initializing Xiaohongshu Publisher...');
      try {
        this.setupEventListeners();
        this.setupCharCounters();
        this.setupDragAndDrop();
        this.setupPreview();
        console.log('Publisher initialized successfully');
      } catch (error) {
        console.error('Error initializing publisher:', error);
      }
    }

    setupEventListeners() {
      const imageUpload = document.getElementById('imageUpload');
      const fileInput = document.getElementById('fileInput');
      const tagsInput = document.getElementById('tagsInput');
      const publishForm = document.getElementById('publishForm');
      const previewToggle = document.getElementById('previewToggle');

      imageUpload.addEventListener('click', (e) => {
        // 删除下面两行
        // e.preventDefault();
        // e.stopPropagation();
        fileInput.click();
      });

      imageUpload.addEventListener('dragover', (e) => {
        e.preventDefault();
        e.stopPropagation();
      });

      imageUpload.addEventListener('drop', (e) => {
        e.preventDefault();
        e.stopPropagation();
      });

      fileInput.addEventListener('change', (e) => this.handleFileSelect(e));
      tagsInput.addEventListener('keypress', (e) => this.handleTagInput(e));
      publishForm.addEventListener('submit', (e) => this.handleSubmit(e));
      previewToggle.addEventListener('click', () => this.togglePreview());

      // 实时预览更新 - 使用防抖和智能触发
      ['title', 'content', 'location'].forEach(id => {
        const element = document.getElementById(id);
        element.addEventListener('input', (e) => {
          // 智能检测：只在内容真正发生变化时触发更新
          const currentValue = e.target.value;
          if (element._lastValue !== currentValue) {
            element._lastValue = currentValue;
            this.updatePreview();
          }
        });

        // 添加字段焦点高亮
        element.addEventListener('focus', () => {
          element.classList.add('active-field');
          console.log(`字段获得焦点: ${id}`);
        });

        element.addEventListener('blur', () => {
          element.classList.remove('active-field');
          console.log(`字段失去焦点: ${id}`);
        });

        // 初始化值跟踪
        element._lastValue = element.value;
      });
    }

    setupPreview() {
      // 初始化预览
      this.updatePreview();
    }

    togglePreview() {
      const previewSection = document.getElementById('previewSection');
      const isShowing = previewSection.classList.contains('mobile-show');

      if (isShowing) {
        previewSection.classList.remove('mobile-show');
        document.body.style.overflow = ''; // Restore scrolling
      } else {
        previewSection.classList.add('mobile-show');
        document.body.style.overflow = 'hidden'; // Prevent background scrolling

        // Ensure preview is updated when shown
        this.updatePreview();
      }
    }

    setupCharCounters() {
      const title = document.getElementById('title');
      const content = document.getElementById('content');
      const titleCounter = document.getElementById('titleCounter');
      const contentCounter = document.getElementById('contentCounter');

      title.addEventListener('input', () => {
        const length = title.value.length;
        titleCounter.textContent = `${length}/50`;
        titleCounter.classList.toggle('warning', length > 40);

        // 实时预览更新 - 包含输入统计信息
        this.updatePreviewWithStats(length, content.value.length);
      });

      content.addEventListener('input', () => {
        const length = content.value.length;
        contentCounter.textContent = `${length}/1000`;
        contentCounter.classList.toggle('warning', length > 800);

        // 实时预览更新 - 包含输入统计信息
        this.updatePreviewWithStats(title.value.length, length);
      });
    }

    updatePreviewWithStats(titleLength, contentLength) {
      // 在控制台显示输入统计（用于调试）
      console.log(`输入统计 - 标题: ${titleLength}/50, 内容: ${contentLength}/1000`);

      // 触发预览更新
      this.updatePreview();
    }

    showUploadProgress(message, type = 'progress') {
      const progress = document.getElementById('uploadProgress');
      if (progress) {
        progress.textContent = message;
        progress.className = `upload-progress show upload-${type}`;
      }
    }

    hideUploadProgress() {
      const progress = document.getElementById('uploadProgress');
      if (progress) {
        progress.className = 'upload-progress';
        setTimeout(() => {
          progress.textContent = '';
        }, 300);
      }
    }

    setupDragAndDrop() {
      const imageUpload = document.getElementById('imageUpload');

      ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        imageUpload.addEventListener(eventName, (e) => e.preventDefault());
      });

      ['dragenter', 'dragover'].forEach(eventName => {
        imageUpload.addEventListener(eventName, () => {
          imageUpload.classList.add('dragover');
        });
      });

      ['dragleave', 'drop'].forEach(eventName => {
        imageUpload.addEventListener(eventName, () => {
          imageUpload.classList.remove('dragover');
        });
      });

      imageUpload.addEventListener('drop', (e) => {
        try {
          e.preventDefault();
          e.stopPropagation();

          const files = Array.from(e.dataTransfer.files);
          if (files.length === 0) {
            console.log('拖拽内容不包含文件');
            return;
          }

          console.log(`拖拽了 ${files.length} 个文件:`,
              files.map(f => ({name: f.name, type: f.type, size: this.formatFileSize(f.size)})));

          // 验证是否有图片文件
          const imageFiles = files.filter(file => file.type.startsWith('image/'));
          if (imageFiles.length === 0) {
            alert('请拖拽图片文件（JPG、PNG、GIF、WebP格式）');
            return;
          }

          if (imageFiles.length !== files.length) {
            console.log(`过滤了 ${files.length - imageFiles.length} 个非图片文件`);
          }

          this.processFiles(imageFiles);

          // 添加成功反馈
          if (imageFiles.length > 0) {
            imageUpload.style.background = '#e8f5e8';
            setTimeout(() => {
              imageUpload.style.background = '';
            }, 500);
          }

        } catch (error) {
          console.error('处理拖拽文件时出错:', error);
          alert('处理拖拽文件时出错: ' + error.message);
        }
      });
    }

    handleFileSelect(e) {
      try {
        const files = Array.from(e.target.files);
        if (files.length === 0) {
          console.log('未选择任何文件');
          return;
        }

        console.log(`选择了 ${files.length} 个文件:`,
            files.map(f => ({name: f.name, type: f.type, size: this.formatFileSize(f.size)})));

        // 验证文件类型
        const imageFiles = files.filter(file => file.type.startsWith('image/'));
        if (imageFiles.length === 0) {
          alert('请选择图片文件（JPG、PNG、GIF、WebP格式）');
          e.target.value = '';
          return;
        }

        if (imageFiles.length !== files.length) {
          console.log(`过滤了 ${files.length - imageFiles.length} 个非图片文件`);
        }

        this.processFiles(imageFiles);

        // 添加成功反馈
        const imageUpload = document.getElementById('imageUpload');
        if (imageFiles.length > 0) {
          imageUpload.style.background = '#e8f5e8';
          setTimeout(() => {
            imageUpload.style.background = '';
          }, 500);
        }

        // 只有在处理完文件后才清空file input的值，让用户可以重新选择相同的文件
        setTimeout(() => {
          e.target.value = '';
        }, 100);

      } catch (error) {
        console.error('处理文件选择时出错:', error);
        alert('处理文件时出错: ' + error.message);
        e.target.value = '';
      }
    }

    processFiles(files) {
      if (!files || files.length === 0) {
        console.log('没有文件需要处理');
        return;
      }

      const remainingSlots = this.maxImages - this.images.length;

      if (files.length > remainingSlots) {
        alert(`最多只能上传 ${this.maxImages} 张图片，还可上传 ${remainingSlots} 张`);
        files.splice(remainingSlots);
      }

      // 显示总体上传进度
      if (files.length > 1) {
        this.showUploadProgress(`正在处理 ${files.length} 张图片...`, 'progress');
      }

      // 逐个处理文件
      files.forEach((file, index) => {
        if (this.images.length < this.maxImages) {
          // 如果是多文件上传，添加延迟避免界面卡顿
          if (files.length > 1) {
            setTimeout(() => {
              this.addImage(file);

              // 最后一个文件处理完成
              if (index === files.length - 1) {
                setTimeout(() => {
                  this.hideUploadProgress();
                }, 1000);
              }
            }, index * 200); // 每个文件延迟200ms
          } else {
            this.addImage(file);
          }
        }
      });
    }

    addImage(file) {
      // 文件验证
      if (!this.validateImageFile(file)) {
        return;
      }

      // 检查是否已存在相同文件
      const fileHash = this.generateFileHash(file);
      if (this.images.some(img => img.fileHash === fileHash)) {
        alert('该图片已存在，请勿重复上传');
        return;
      }

      // 显示上传进度
      this.showUploadProgress(`正在读取: ${file.name}...`, 'progress');

      const reader = new FileReader();

      reader.onloadstart = () => {
        console.log(`开始读取文件: ${file.name}`);
      };

      reader.onprogress = (event) => {
        if (event.lengthComputable) {
          const percentComplete = Math.round((event.loaded / event.total) * 100);
          this.showUploadProgress(`读取中: ${percentComplete}%`, 'progress');
        }
      };

      reader.onload = (e) => {
        try {
          this.images.push({
            id: Date.now() + Math.random(),
            src: e.target.result,
            file: file,
            fileHash: fileHash,
            uploadTime: new Date().toISOString()
          });
          this.renderImagePreview();
          this.updatePreview();

          // 显示成功状态
          this.showUploadProgress(`✅ ${file.name} 上传成功!`, 'success');
          console.log(`图片上传成功: ${file.name} (${this.formatFileSize(file.size)})`);

          // 2秒后隐藏进度提示
          setTimeout(() => {
            this.hideUploadProgress();
          }, 2000);

        } catch (error) {
          console.error('处理图片数据时出错:', error);
          this.showUploadProgress(`❌ 处理失败: ${file.name}`, 'error');
          alert('处理图片时出错，请重试');

          setTimeout(() => {
            this.hideUploadProgress();
          }, 3000);
        }
      };

      reader.onerror = (error) => {
        console.error('文件读取错误:', error);
        this.showUploadProgress(`❌ 读取失败: ${file.name}`, 'error');
        alert(`读取文件失败: ${file.name}`);

        setTimeout(() => {
          this.hideUploadProgress();
        }, 3000);
      };

      reader.onabort = () => {
        console.log('文件读取被取消');
        this.showUploadProgress(`⏹️ 已取消: ${file.name}`, 'error');

        setTimeout(() => {
          this.hideUploadProgress();
        }, 2000);
      };

      // 开始读取文件
      try {
        reader.readAsDataURL(file);
      } catch (error) {
        console.error('开始读取文件时出错:', error);
        this.showUploadProgress(`❌ 无法读取: ${file.name}`, 'error');
        alert('无法读取该文件，请检查文件格式');

        setTimeout(() => {
          this.hideUploadProgress();
        }, 3000);
      }
    }

    validateImageFile(file) {
      // 文件类型验证
      const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
      if (!validTypes.includes(file.type)) {
        alert(`不支持的文件格式: ${file.type}\n请上传 JPG、PNG、GIF 或 WebP 格式的图片`);
        return false;
      }

      // 文件大小验证 (最大 10MB)
      const maxSize = 10 * 1024 * 1024; // 10MB
      if (file.size > maxSize) {
        alert(`文件过大: ${this.formatFileSize(file.size)}\n最大支持 ${this.formatFileSize(
            maxSize)}`);
        return false;
      }

      // 文件完整性检查
      if (file.size === 0) {
        alert('文件为空，请选择有效的图片文件');
        return false;
      }

      return true;
    }

    generateFileHash(file) {
      // 简单的文件哈希生成（基于文件名、大小和最后修改时间）
      return `${file.name}-${file.size}-${file.lastModified}`;
    }

    formatFileSize(bytes) {
      if (bytes === 0) {
        return '0 Bytes';
      }
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    renderImagePreview() {
      const preview = document.getElementById('imagePreview');
      preview.innerHTML = '';

      this.images.forEach((image, index) => {
        const item = document.createElement('div');
        item.className = 'preview-item';
        item.innerHTML = `
                        <img src="${image.src}" alt="预览图片 ${index + 1}">
                        <button type="button" class="remove-btn" onclick="publisher.removeImage(${image.id})">×</button>
                    `;
        preview.appendChild(item);
      });
    }

    removeImage(id) {
      this.images = this.images.filter(img => img.id !== id);
      this.renderImagePreview();
      this.updatePreview();
    }

    handleTagInput(e) {
      if (e.key === 'Enter') {
        e.preventDefault();
        const value = e.target.value.trim();
        if (value && !this.tags.includes(value)) {
          this.tags.push(value);
          this.renderTags();
          this.updatePreview();
          e.target.value = '';
        }
      }
    }

    renderTags() {
      const container = document.getElementById('tagsContainer');
      container.innerHTML = '';

      this.tags.forEach(tag => {
        const tagElement = document.createElement('div');
        tagElement.className = 'tag';
        tagElement.innerHTML = `
                        #${tag}
                        <button type="button" class="remove-tag" onclick="publisher.removeTag('${tag}')">×</button>
                    `;
        container.appendChild(tagElement);
      });

      const input = document.createElement('input');
      input.type = 'text';
      input.className = 'tag-input';
      input.placeholder = '添加标签...';
      input.addEventListener('keypress', (e) => this.handleTagInput(e));
      container.appendChild(input);
    }

    removeTag(tag) {
      this.tags = this.tags.filter(t => t !== tag);
      this.renderTags();
      this.updatePreview();
    }

    updatePreview() {
      // Clear any existing debounce timer
      if (this.previewDebounceTimer) {
        clearTimeout(this.previewDebounceTimer);
      }

      // Show updating indicator
      this.showUpdatingIndicator();

      // Set up debounced preview update (300ms delay)
      this.previewDebounceTimer = setTimeout(() => {
        this.performPreviewUpdate();
        this.hideUpdatingIndicator();
      }, 300);
    }

    showUpdatingIndicator() {
      const indicator = document.getElementById('previewUpdating');
      if (indicator) {
        indicator.classList.add('show');
      }
    }

    hideUpdatingIndicator() {
      const indicator = document.getElementById('previewUpdating');
      if (indicator) {
        indicator.classList.remove('show');
      }
    }

    performPreviewUpdate() {
      const now = Date.now();

      // Throttle updates to prevent excessive re-renders (minimum 100ms between updates)
      if (now - this.lastPreviewUpdate < 100) {
        return;
      }

      this.lastPreviewUpdate = now;

      try {
        const title = document.getElementById('title').value.trim();
        const content = document.getElementById('content').value.trim();
        const location = document.getElementById('location').value.trim();

        const mobileScreen = document.getElementById('mobileScreen');

        if (this.images.length === 0) {
          mobileScreen.innerHTML = `
                          <div class="no-images">
                              <div class="no-images-icon">📱</div>
                              <div>左侧添加图片查看预览效果</div>
                          </div>
                      `;
          return;
        }

        const firstImage = this.images[0].src;
        const displayTitle = title || '标题预览';
        const displayContent = content || '正文内容预览，在这里会显示你输入的笔记内容...';
        const displayLocation = location || '未知位置';

        // Only update if content has actually changed
        const newContent = this.generatePreviewHTML(displayTitle, displayContent, displayLocation,
            firstImage);
        if (mobileScreen.innerHTML !== newContent) {
          mobileScreen.innerHTML = newContent;
          console.log('Preview updated at', new Date().toLocaleTimeString());
        }
      } catch (error) {
        console.error('Error updating preview:', error);
      }
    }

    generatePreviewHTML(title, content, location, firstImage) {
      return `
                    <div class="mobile-header">
                        <div class="mobile-avatar">我</div>
                        <div class="mobile-user-info">
                            <div class="mobile-username">我的昵称</div>
                            <div class="mobile-time">刚刚</div>
                        </div>
                        <button class="mobile-follow">关注</button>
                    </div>
                    
                    <div class="mobile-images">
                        <div class="mobile-image-container">
                            <img src="${firstImage}" class="mobile-image" alt="预览图片">
                            ${this.images.length > 1
          ? `<div class="mobile-image-indicator">1/${this.images.length}</div>` : ''}
                        </div>
                    </div>
                    
                    <div class="mobile-content">
                        <div class="mobile-title">${this.escapeHtml(title)}</div>
                        <div class="mobile-text">${this.escapeHtml(content)}</div>
                        ${this.tags.length > 0 ? `
                            <div class="mobile-tags">
                                ${this.tags.map(
          tag => `<span class="mobile-tag">#${this.escapeHtml(tag)}</span>`).join('')}
                            </div>
                        ` : ''}
                        <div class="mobile-location">
                            <span>📍</span>
                            <span>${this.escapeHtml(location)}</span>
                        </div>
                    </div>
                    
                    <div class="mobile-actions">
                        <div class="mobile-action">
                            <span>❤️</span>
                            <span>点赞</span>
                        </div>
                        <div class="mobile-action">
                            <span>💬</span>
                            <span>评论</span>
                        </div>
                        <div class="mobile-action">
                            <span>⭐</span>
                            <span>收藏</span>
                        </div>
                        <div class="mobile-action">
                            <span>↗️</span>
                            <span>分享</span>
                        </div>
                    </div>
                `;
    }

    escapeHtml(text) {
      const div = document.createElement('div');
      div.textContent = text;
      return div.innerHTML;
    }

    async handleSubmit(e) {
      e.preventDefault();

      const title = document.getElementById('title').value.trim();
      const content = document.getElementById('content').value.trim();
      const location = document.getElementById('location').value.trim();

      if (!this.validateForm(title, content)) {
        return;
      }

      const publishBtn = document.getElementById('publishBtn');
      publishBtn.disabled = true;
      publishBtn.textContent = '📤 发布中...';

      try {
        // 准备发布数据
        const formData = new FormData();
        formData.append('title', title);
        formData.append('content', content);
        formData.append('location', location);
        
        // 添加标签
        this.tags.forEach(tag => {
          formData.append('tags', tag);
        });
        
        // 添加图片文件
        this.images.forEach((image, index) => {
          formData.append('images', image.file);
        });

        // 调用发布接口
        const response = await fetch('/auto/publish', {
          method: 'POST',
          body: formData
        });

        if (response.ok) {
          const result = await response.json();
          if (result.success) {
            alert('🎉 发布成功！你的笔记已分享到社区');
            this.resetForm();
          } else {
            alert('❌ 发布失败：' + (result.message || '未知错误'));
          }
        } else {
          throw new Error('网络请求失败，状态码：' + response.status);
        }
      } catch (error) {
        alert('❌ 发布失败，请重试');
        console.error('Publish error:', error);
      } finally {
        publishBtn.disabled = false;
        publishBtn.textContent = '🚀 发布笔记';
      }
    }

    validateForm(title, content) {
      if (this.images.length === 0) {
        alert('📸 请至少上传一张图片');
        return false;
      }

      if (!title) {
        alert('✏️ 请输入标题');
        return false;
      }

      if (title.length > 50) {
        alert('✏️ 标题不能超过50个字符');
        return false;
      }

      if (!content) {
        alert('📝 请输入内容');
        return false;
      }

      if (content.length > 1000) {
        alert('📝 内容不能超过1000个字符');
        return false;
      }

      return true;
    }

    simulatePublish(data) {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log('Publishing data:', data);
          resolve({success: true, id: Date.now()});
        }, 2000);
      });
    }

    resetForm() {
      document.getElementById('publishForm').reset();
      this.images = [];
      this.tags = [];
      this.renderImagePreview();
      this.renderTags();
      this.updatePreview();
      document.getElementById('titleCounter').textContent = '0/50';
      document.getElementById('contentCounter').textContent = '0/1000';
    }
  }

  // 初始化发布器
  const publisher = new XiaohongshuPublisher();

  // 添加一些示例功能
  document.addEventListener('DOMContentLoaded', () => {
    // 添加示例标签提示
    const tagsInput = document.getElementById('tagsInput');
    tagsInput.addEventListener('focus', () => {
      if (tagsInput.value === '') {
        tagsInput.placeholder = '例如: 美食, 旅行, 穿搭, 美妆...';
      }
    });

    tagsInput.addEventListener('blur', () => {
      tagsInput.placeholder = '添加话题标签，按回车确认';
    });
  });
</script>
</body>
</html>